import random
import qrcode
import os
import shutil
import docx
from docx.shared import Inches
import math
import tkinter
import tkinter.messagebox
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT

class Qrcodetool():

    number = "1234567890"
    path = 'qrcode'
    suffix = '.png'
    docname = 'Qrcodedoc.docx'

    # cnt表示多少个码，num表示一个码多少位数
    def __init__(self, cnt, num):
        self.cnt = cnt
        self.num = num

    # 创建文件夹函数
    def mkdir(self):
        isexists = os.path.exists(self.path)  # 判断文件夹路径是否存在
        if isexists:  # 如果文件夹路径存在，则删除
            shutil.rmtree(self.path)
        os.mkdir(self.path)  # 创建要创建的文件夹

    # 生成二维码对应的数
    def genQrnumbers(self):
        numbers = []
        for i in range(self.cnt):
            qrnumber = ''
            for j in range(self.num):
                qrnumber = qrnumber + str(random.choice(self.number))
            numbers.append(qrnumber)
        print(numbers)
        return numbers

    # 生成二维码到目录中
    def genQrcodes(self, numbers):
        self.mkdir()
        for i in range(0, len(numbers)):
            encoder = qrcode.make(numbers[i])
            encoder.save(self.path + '/' + numbers[i] + self.suffix)

    # 合成到Word文档中
    def genWord(self, numbers):
        wdoc = docx.Document()
        t_cols = 4
        qrcodeMax = len(numbers)
        qrcodeNum = 0
        t_rows = math.ceil(len(numbers)/t_cols)
        table = wdoc.add_table(rows=t_rows, cols=t_cols)
        for i in range(0, t_rows):
            for j in range(0, t_cols):
                if qrcodeNum < qrcodeMax:
                    # run = table.cell(i, j).paragraphs[0].add_run()
                    paragraph = table.cell(i, j).add_paragraph()
                    # paragraph居中显示
                    paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
                    # 上面显示二维码
                    paragraph.add_run().add_picture(self.path + '/' + numbers[qrcodeNum] + self.suffix, width=Inches(1.3), height=Inches(1.3))
                    # 下面显示二维码数字
                    paragraph.add_run().text = numbers[qrcodeNum]
                    qrcodeNum += 1
        # wdoc.add_picture(self.path + '/'+ numbers[i] + self.suffix, width=Inches(2.0), height=Inches(2.0))
        wdoc.save(self.docname)

    # 入口方法
    def qrcodego(self):
        numbers = self.genQrnumbers()
        self.genQrcodes(numbers)
        self.genWord(numbers)

Qrcodetool(100, 12).qrcodego()

# tkinter.messagebox.showinfo("提示", '提示信息')
